<template>
  <el-card class="margin-top">
    <div slot="header" class="clearfix relative">
      <span class="title-icon margin-right">应收信息</span>
      <el-button
        v-if="billStatus === 1 && accountPeriod >= 20"
        size="mini"
        type="primary"
        @click="confirmAbroadBillStatus"
        >确认账单信息</el-button
      >
    </div>

    <el-table
      ref="multipleTable"
      size="mini"
      :data="receivableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="44" align="center"> -->
      <!-- </el-table-column> -->

      <ex-table-column
        v-for="item in tabColumns"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :auto-fit="true"
        :fit-header="true"
      >
        <template slot-scope="scope">
          <template v-if="item.map">
            {{ publicData[item.map][scope.row[item.prop]] }}
          </template>
          <template v-else>
            {{ scope.row[item.prop] }}
          </template>
        </template>
      </ex-table-column>
    </el-table>
  </el-card>
</template>

<script>
import { clone } from '@/utils/clone'
import { mapGetters } from 'vuex'
import { confirmAbroadBillStatus } from '@/api/abroadWaybill'
import { getInfo } from '@/api/user'
export default {
  props: {
    receivableData: {
      type: Array,
      default: function() {
        return []
      }
    },
    billStatus: {
      type: Number,
      default: 1
    },
    waybillId: {
      type: Number | String,
      default: 0
    }
  },
  computed: {
    ...mapGetters(['publicData'])
  },

  data() {
    return {
      accountPeriod: '',
      restaurants: [],
      selectionList: [],
      selectionPayableList: [],
      isChangeReceivable: false,
      isChangePayable: false,
      tabColumns: [
        { prop: 'serCusId', label: '公司', map: 'customerNameShortMap' },
        { prop: 'costName', label: '费用名称', map: 'configPayNameMap' },
        { prop: 'unitPrice', label: '单价' },
        { prop: 'count', label: '数量' },
        { prop: 'currency', label: '币种' },
        { prop: 'totalCost', label: '总额' },
        { prop: 'remain', label: '余额' },
        // { prop: 'inputUser', label: '创建人', map: 'userAll' },
        // { prop: 'lastOperator', label: '修改人', map: 'userAll' },
        { prop: 'cdate', label: '创建日期' },
        { prop: 'accountDate', label: '费用日期' },
        { prop: 'remark', label: '备注' }
      ]
    }
  },
  mounted() {
    this.getInfo()
    console.log('billStatus', this.billStatus)
  },
  methods: {
    handleSelectionChange(val) {
      console.log(
        '%cval: ',
        'color: MidnightBlue; background: Aquamarine;',
        val
      )
      this.selectionList = val
    },
    payableSelectionChange(val) {
      this.selectionPayableList = val
    },
    async getInfo() {
      const user = await getInfo({})
      if (user) {
        this.accountPeriod = user.accountPeriod
        console.log('accountPeriod', this.accountPeriod)
      }
    },
    confirmAbroadBillStatus() {
      this.$confirm('是否确认账单信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          confirmAbroadBillStatus({ id: parseInt(this.waybillId) }).then(
            res => {
              if (res.code === 200) {
                this.$message.success('操作成功')
                console.log(res)
              } else {
                this.$$message.error('系统内部异常')
              }
            }
          )
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    changeReceivable() {
      if (this.isChangeReceivable) {
        this.$confirm('确认保存修改？')
          .then(_ => {
            // TODO 保存操作
            let flag = true
            for (const i of this.receivableData) {
              flag = this.checkRule(i)
            }
            if (!flag) return
            this.isChangeReceivable = false
          })
          .catch(_ => {})
      } else {
        this.isChangeReceivable = true
      }
    },
    changePayable() {
      if (this.isChangePayable) {
        this.$confirm('确认保存修改？')
          .then(_ => {
            // TODO 保存操作
            let flag = true
            for (const i of this.payableData) {
              flag = this.checkRule(i)
            }
            if (!flag) return
            this.isChangePayable = false
          })
          .catch(_ => {})
      } else {
        this.isChangePayable = true
      }
    },

    addselect(type) {
      if (type === 'receivable') {
        this.receivableData = this.addSelectRow(this.receivableData)
      } else {
        this.payableData = this.addSelectRow(this.payableData)
      }
    },
    addSelectRow(arrList) {
      const obj = {
        serCusId: '',
        costName: '',
        configPayType: '',
        configPayTypec: '',
        responsibleBelongGroupId: '',
        // inputUser: '',
        // lastOperator: '',
        unitPrice: '',
        count: '',
        currency: '',
        totalCost: '',
        remain: '',
        billType: '',
        amoebaSubjectId: '',
        accountDate: new Date().toLocaleDateString(),
        creatDate: new Date().toLocaleDateString(),
        remark: ''
      }
      console.log('obj', obj)
      arrList.push(obj)
      return arrList
    },

    addPayableRow(data) {
      this.payableData.splice(data.$index + 1, 0, {
        serCusId: data.row.serCusId,
        costName: data.row.costName,
        configPayType: '',
        configPayTypec: '',
        responsibleBelongGroupId: '',
        // inputUser: '',
        // lastOperator: '',
        unitPrice: data.row.unitPrice,
        count: data.row.count,
        currency: data.row.currency,
        totalCost: data.row.totalCost,
        remain: data.row.totalCost,
        billType: data.row.billType,
        amoebaSubjectId: '',
        accountDate: new Date().toLocaleDateString(),
        creatDate: new Date().toLocaleDateString(),
        remark: ''
      })
    },
    addRow(data) {
      this.receivableData.splice(data.$index + 1, 0, {
        serCusId: data.row.serCusId,
        costName: data.row.costName,
        configPayType: '',
        configPayTypec: '',
        responsibleBelongGroupId: '',
        // inputUser: '',
        // lastOperator: '',
        unitPrice: data.row.unitPrice,
        count: data.row.count,
        currency: data.row.currency,
        totalCost: data.row.totalCost,
        remain: data.row.totalCost,
        billType: data.row.billType,
        amoebaSubjectId: '',
        accountDate: new Date().toLocaleDateString(),
        creatDate: new Date().toLocaleDateString(),
        remark: ''
      })
    },
    removeRow(row) {
      if (this.receivableData.length > 1) {
        this.receivableData.splice(row.$index, 1)
      }
    },
    removePayableRow(row) {
      if (this.payableData.length > 1) {
        this.payableData.splice(row.$index, 1)
      }
    },
    copyToPayable(data) {
      this.$confirm('确认复制到应付？')
        .then(_ => {
          const target = clone(data.row)
          if (this.checkRule(target)) {
            target.accountDate = target.creatDate = new Date().toLocaleDateString()
            // TODO 公司名=运单对应清关代理 || ''
            this.payableData.push(target)
            // TODO 保存操作 更新数据
          }
        })
        .catch(_ => {})
    },
    copyToReceivable(data) {
      this.$confirm('确认复制到应收？')
        .then(_ => {
          const target = clone(data.row)
          if (this.checkRule(target)) {
            target.accountDate = target.creatDate = new Date().toLocaleDateString()
            // TODO 公司名等于当前客户
            this.receivableData.push(target)
            // TODO 保存操作 更新数据
          }
        })
        .catch(_ => {})
    },
    checkRule(i) {
      if (!i.serCusId) {
        this.$message.error('请填写公司名')
        return false
      } else if (!i.costName) {
        this.$message.error('请填写费用名称')
        return false
      } else if (i.configPayTypec === 'C3' && !i.responsibleBelongGroupId) {
        this.$message.error('请填写责任人')
        return false
      } else if (!i.count) {
        this.$message.error('请填写数量')
        return false
      } else if (!i.currency) {
        this.$message.error('请填写币种')
        return false
      } else if (!i.unitPrice) {
        this.$message.error('请填写单价')
        return false
      } else if (!i.billType) {
        this.$message.error('请填写账单类型')
        return false
      }

      return true
    },
    changeCount(val, scope, name) {
      if (name === 'receivable') {
        const target = this.receivableData[scope.$index]
        const totalCost = (target.unitPrice * 100 * target.count) / 100
        this.$set(this.receivableData[scope.$index], 'totalCost', totalCost)
      } else {
        const target = this.payableData[scope.$index]
        const totalCost = (target.unitPrice * 100 * target.count) / 100
        this.$set(this.payableData[scope.$index], 'totalCost', totalCost)
      }
      // ((scope.row['unitPrice']* 100) *(scope.row['unitPrice'] *100))/10000
    },
    changeUnitPrice(val, scope, name) {
      console.log(
        '%cname: ',
        'color: MidnightBlue; background: Aquamarine;',
        name
      )
      console.log(
        '%cscope: ',
        'color: MidnightBlue; background: Aquamarine;',
        scope
      )
      console.log(
        '%cval: ',
        'color: MidnightBlue; background: Aquamarine;',
        val
      )

      if (name === 'receivable') {
        const target = this.receivableData[scope.$index]
        const totalCost = (target.unitPrice * 100 * target.count) / 100
        this.$set(this.receivableData[scope.$index], 'totalCost', totalCost)
      } else {
        const target = this.payableData[scope.$index]
        const totalCost = (target.unitPrice * 100 * target.count) / 100
        this.$set(this.payableData[scope.$index], 'totalCost', totalCost)
      }
    }
  }
}
</script>

<style scoped>
.border-lr {
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}
/deep/ .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
<style>
.handsontable th {
  background: #fff;
  color: #2c3e50;
  text-align: left;
  font-weight: bold;
}

.el-card__body {
  color: #606266;
}
.handsontable th:first-child,
.handsontable th:nth-child(2),
.handsontable td:first-of-type,
.handsontable tr th,
.handsontable tr td,
.handsontable tr:first-child th,
.handsontable tr:first-child td {
  border-color: #ebeef5;
}
</style>
